import { FC, useEffect } from 'react';
import { Button, Form, Input, message } from 'antd';

import styles from './index.less';
import { willLoginApi, loginApi } from '@/utils/api';

// todo JSEncrypt用于公钥加密的，构造函数
import JSEncrypt from 'jsencrypt';

import { history } from 'umi';

let publicKey: string;
const Index: FC = () => {
  useEffect(() => {
    (async () => {
      const res = await willLoginApi();
      publicKey = res.publicKey;
      console.log(publicKey);
    })();
  }, []);

  const onFinish = async (values: any) => {
    // console.log('Success:', values);
    // todo 拿到加密实例
    const encrypt = new JSEncrypt();
    // todo 将公钥当作参数传入
    encrypt.setPublicKey(publicKey);
    // todo 传入登录信息得到密文
    const info = encrypt.encrypt(JSON.stringify(values));
    console.log(info);

    const res = await loginApi({ info });
    if (res.status === 0) {
      message.success(res.msg);
      localStorage.setItem('username', values.username);
      localStorage.setItem('token', res.token);
      localStorage.setItem('auth', JSON.stringify(res.auth));
      history.push('/admin');
    } else {
      message.error(res.msg);
    }
  };
  return (
    <div className={styles.wrap}>
      <Form
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="Username"
          name="username"
          rules={[{ required: true, message: 'Please input your username!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="Password"
          name="password"
          rules={[{ required: true, message: 'Please input your password!' }]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default Index;
